package memberrank

import (
	"context"
	"strconv"

	"mall/common/modelx"
	"mall/common/moneyx"
	enum "mall/service/backend/common/enum/setting"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/backend/common/utils/pointy"
	"mall/service/setting/model"
	"mall/service/setting/rpc/internal/svc"
	"mall/service/setting/rpc/internal/utils/errorhandler"
	"mall/service/setting/rpc/types/setting"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendGetMemberRankByIdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendGetMemberRankByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendGetMemberRankByIdLogic {
	return &BackendGetMemberRankByIdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// group: memberrank
func (l *BackendGetMemberRankByIdLogic) BackendGetMemberRankById(in *setting.MemberRankIdReq) (*setting.MemberRankInfo, error) {
	if in.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	res, err := l.svcCtx.MemberRank.FindOne(l.ctx, in.Id)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	var restrictions []*setting.MemberRankRestrictionInfo
	if in.WithRestrictions != nil && *in.WithRestrictions > 0 {
		filterMap := make(map[string]map[string][]any)
		filterMap[model.SysMemberRankRestrictionColumns.RankID] = map[string][]any{
			"equalTo": []any{in.Id},
		}
		list, _, err := l.svcCtx.MemberRank.GetRestrictionList(l.ctx, model.M{
			"orderBy": model.SysMemberRankRestrictionColumns.Sort,
		}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if len(list) > 0 {
			for _, v := range list {
				restrictions = append(restrictions, &setting.MemberRankRestrictionInfo{
					Id:        &v.RestrictionID,
					RankId:    &v.RankID,
					TaskId:    &v.TaskID,
					Threshold: pointy.GetPointer(uint32(v.Threshhold)),
					Sort:      pointy.GetPointer(uint32(v.Sort)),
					Status:    pointy.GetPointer(uint32(v.Status)),
				})
			}
		}
	}
	var rules []*setting.MemberRankRuleInfo
	if in.WithRules != nil && *in.WithRules > 0 {
		filterMap := make(map[string]map[string][]any)
		filterMap[model.SysMemberRankRuleColumns.RankID] = map[string][]any{
			"equalTo": []any{in.Id},
		}
		list, _, err := l.svcCtx.MemberRank.GetRuleList(l.ctx, model.M{
			"orderBy": model.SysMemberRankRuleColumns.Sort,
		}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if len(list) > 0 {
			for _, v := range list {
				var regions *string
				var value *string
				switch v.RuleType {
				case enum.MemberRankRuleTypeDiscount, enum.MemberRankRuleTypeGems:
					switch v.Mode {
					case enum.MemberRankRuleModeAmount, enum.MemberRankRuleModeFixed:
						value = pointy.GetPointer(moneyx.FormatAmount(int64(v.Value)))
					case enum.MemberRankRuleModeDiscount:
						value = pointy.GetPointer(strconv.FormatInt(int64(v.Value), 10))
					}
				case enum.MemberRankRuleTypeFreeShipping:
					if v.Regions.Valid {
						regions = pointy.GetPointer(string(v.Regions.JSON))
					}
				case enum.MemberRankRuleTypeExtraPoint:
					value = pointy.GetPointer(strconv.FormatInt(int64(v.Value), 10))
				case enum.MemberRankRuleTypeCoupon:
					value = pointy.GetPointer(strconv.FormatInt(int64(v.Value), 10))
				}
				rules = append(rules, &setting.MemberRankRuleInfo{
					Id:         &v.RuleID,
					RankId:     &v.RankID,
					RuleType:   pointy.GetPointer(uint32(v.RuleType)),
					Regions:    regions,
					Mode:       pointy.GetPointer(uint32(v.Mode)),
					Value:      value,
					PeriodType: pointy.GetPointer(uint32(v.PeriodType)),
					Quota:      pointy.GetPointer(uint32(v.Quota)),
					Sort:       pointy.GetPointer(uint32(v.Sort)),
					Status:     pointy.GetPointer(uint32(v.Status)),
				})
			}
		}
	}

	return &setting.MemberRankInfo{
		Id:             &res.ID,
		Name:           &res.Name,
		Code:           &res.Code,
		Description:    &res.Description,
		Remark:         &res.Remark,
		PicId:          &res.PicID,
		PicUrl:         &res.PicURL,
		PointThreshold: pointy.GetPointer(uint32(res.PointThreshold)),
		IsDefault:      pointy.GetPointer(uint32(res.IsDefault)),
		Sort:           pointy.GetPointer(uint32(res.Sort)),
		Status:         pointy.GetPointer(uint32(res.Status)),
		CreatedAt:      pointy.GetPointer(modelx.FormatTime(res.CreatedAt, "")),
		UpdatedAt:      pointy.GetPointer(modelx.FormatTime(res.UpdatedAt, "")),
		DeletedAt:      pointy.GetPointer(modelx.FormatNullDotTime(res.DeletedAt, "")),
		Restrictions:   restrictions,
		Rules:          rules,
	}, nil
}
